#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <pthread.h>


#define THRNUM 4

static void *thread_func(void *p);
static pthread_mutex_t mutex[THRNUM];




int main()
{

    int i;
    int err;
    struct NUM *p;
    pthread_t tid[THRNUM];
    for (i = 0; i < THRNUM; i++)
    {
        pthread_mutex_init(mutex+i , NULL);// 每个线程都初始化一把自己的锁
        pthread_mutex_lock(mutex+i);// 初始化后把自己锁上
        err = pthread_create(tid + i , NULL, thread_func, (void*)i);
        if (err > 0)
        {
            fprintf(stderr, "pthread create error\n");
            exit(1);
        }
    }

    alarm(5);
    pthread_mutex_unlock(mutex);// 解开a的锁
    for (i = 0; i < THRNUM; i++)
    {
        pthread_join(tid[i],NULL);
    }
    exit(0);
}

static int next (int n)
{
    if(n ==THRNUM-1)
        return 0;
    else
        return n+1;
}


static void *thread_func(void *p)
{
    int n = (int)p;
    int c = 'a' + n ;
    while(1)
    {
        pthread_mutex_lock(mutex + n);
        write(1,&c,1);
        pthread_mutex_unlock(mutex + next(n));

    }
    pthread_exit(NULL);
}
